import axios from 'axios'
import FormData from 'form-data'
import qs from 'query-string'
axios.defaults.timeout = 100000
// axios.defaults.baseURL = typeof window != 'undefined'?"/":"http://127.0.0.1:8000";

axios.interceptors.request.use(config => ({
  ...config,
  // url: '//test-mws.dn8188.com' + config.url
  // url: '//mws.dn8188.com' + config.url
  url: 'http://127.0.0.1:8066' + config.url

}),
(error) => error)
axios.interceptors.response.use(
  (response) => response,
  (error) => {
    console.error(`axios-error: ${error?.config?.method?.toUpperCase()} ${error?.config?.url} ${error}`)
    if (error?.response?.status === 401) {
      // window.location.href = '/prompt/reenter'
    }
    if (error?.response?.status === 403) {
      window.location.href = '/prompt/noPermission'
    }
    return {
      data: {
        data: null,
        state: 'warn',
        message: '请稍后重试',
        code: error?.response?.status
      }
    }
  }
)

const formatUrl = (url: string) => {
  let tempUrl = url
  if (url.indexOf('?') > -1) {
    tempUrl += '&_t=' + Date.now()
  } else {
    tempUrl += '?_t=' + Date.now()
  }
  return tempUrl
}

function get(url: string, params?: { [k: string]: any }): Promise<any> {
  return new Promise((resolve, reject) => {
    const tempUrl = formatUrl(url)
    axios.get(tempUrl, { params }).then((response) => {
      resolve(response?.data)
      // console.info(`fetch: GET ${tempUrl}  params:${qs.stringify(params || {})} code:${response?.status}}`)
    })
      .catch((error) => reject(error))
  })
}

function post(url: string, data?: { [k: string]: any }): Promise<any> {
  return new Promise((resolve, reject) => {
    const tempUrl = formatUrl(url)
    axios.post(tempUrl, data).then(
      (response) => {
        // console.info(`fetch: POST ${tempUrl} params:${qs.stringify(data || {})} code:${response?.status}}`)
        resolve(response.data)
      },
      (err) => reject(err)
    )
  })
}

function form(url: string, data?: { [k: string]: any }): Promise<any> {
  return new Promise((resolve, reject) => {
    const tempUrl = formatUrl(url)
    const fromd = new FormData()
    for (const key in data) {
      fromd.append(key, data[key])
    }
    const formHeaders = typeof fromd.getHeaders !== 'function' ? {} : fromd?.getHeaders()
    axios.post(tempUrl, fromd, {
      headers: {
        ...formHeaders
      }
    }).then(
      (response) => {
        console.info(`fetch: form ${tempUrl} params:${qs.stringify(data || {})} code:${response?.status}}`)
        resolve(response.data)
      },
      (err) => reject(err)
    )
  })
}

export { get, post, form }
